<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/17
 * Time: 下午2:48
 * Describe:
 */

namespace services\models;

use Yii;
class Messages extends \common\models\Messages
{
    public $redis;
    public function init()
    {
        $this->redis = Yii::$app->redis_old;
        parent::init();
    }

    /*
	 * 发送消息 参数依次为:发送人， 接收人， 标题，内容， 类别（类别1会员消息2系统消息3快递消息4好友申请） 好友间发送消息，无需标题
	 */
    public static function addMessage($post_member, $receive_member, $title, $content, $category) {
        if ($post_member == 0)
            $post_member = 1;

        $time = time ();
        $new = new static;
        $new->add_time = date('Y-m-d H:i:s', $time);
        $new->post_member = $post_member;
        $new->receive_member =$receive_member;
        $new->content=$content;
        $new->category=$category;

        $new->title =$title;

        if(!$new->save()){
            return false;
        }

        // 消息详情
        $new->redis->hset ( "Messages", $new->no, serialize ( $new->toArray() ) );
        // 我发送的信息

        // 添加消息到用户列表
        if ($post_member != 1) {
            $new->redis->zadd ( "Friend_M_{$post_member}_{$receive_member}", $time, $new->no ); // 发送列表
            $new->redis->hset ( "M_{$post_member}", "last_message_time", $time ); // 更新最后发送消息时间　判断是否用户在线时用
            $new->redis->zadd ( "Friend_Message_{$post_member}", $time, $receive_member ); // 送消息列表
        } else {
            // 系统消息分类　Leo @2014.04.25
            $new->redis->zadd ( "Friend_M_sys{$category}_{$receive_member}", "2" . $time, $new->no );
        }
        $new->redis->zadd ( "Friend_M_{$receive_member}_{$post_member}", "2" . $time, $new->no ); // 添加新消息到接收者消息列表

        // 更新该用户为接收者未读
        $new->redis->zadd ( "Friend_Message_{$receive_member}", '2' . $time, $post_member ); // 设置接收者的收到消息的好友列表

        return true;
    }
    
    /*
     * 未读消息好友数　
     */
    public static  function newMessagesCount($uid) {
        $f = new static;
        $records = $f->redis->zrevrangebyscore ( "Friend_Message_{$uid}", 30000000000, 2000000000, array (
            'withscores' => TRUE,
            'limit' => array (
                0,
                10
            )
        ) );
        
        if (empty ( $records ))
            return 0;
    
            $num = 0;
            foreach ( $records as $friend => $score ) {
                //2014.05.04 Leo ,未读消息数，不过滤系统消息
                /* if ($friend == 1)
                 continue; */
                $num += $f->redis->zcount ( "Friend_M_{$uid}_{$friend}", 20000000000, 30000000000 );
                if ($num > 10)
                    return '10+';
            }
            return $num > 10 ? '10+' : $num;
    }

}